package com.web.qualification.service;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.web.common.BaseResult;
import com.web.common.PendingAmend;
import com.web.common.enums.BaseStatus;
import com.web.customer.entity.Customer;
import com.web.pendingList.entity.PendingList;
import com.web.pendingList.service.PendingListService;
import com.web.qualification.entity.CustomerQualification;
import com.web.qualification.mapper.CustomerQualificationMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

/**
 * @author wenzhuo
 * @create 2024-05-08 2024/5/8
 */

@Service
public class CustomerQualificationService implements PendingAmend {

    @Resource
    private CustomerQualificationMapper qualificationMapper;

    @Resource
    private PendingListService pendingListService;

    public List<CustomerQualification> getAllCustomerQualification(CustomerQualification qualification){
        return  qualificationMapper.getQualificationList(qualification);
    }

    @Override
    @Transactional
    public BaseResult rejectAddPending(PendingList pendingTxn) {


        //查询CustomerQualification数据是否存在
        CustomerQualification qualification = checkQualification(pendingTxn.getPendingNum());
        if(qualification == null){
            return new BaseResult(BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getCode(),BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getDesc());
        }

        //如果存在就将CustomerQualification数据进行物理删除
        if(qualificationMapper.physicsDeleteQualification(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        //修改审批数据的状态
        if(pendingListService.updatePendingTxn(PendingList.makeReject(pendingTxn)) < 0){
            return new BaseResult(BaseStatus.PENDING__DATA_EXCEPTION.getCode(),BaseStatus.PENDING__DATA_EXCEPTION.getDesc());
        }

        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.PENDING_REJECT_SUCCESS.getDesc());
    }

    @Override
    @Transactional
    public BaseResult approveAddPending(PendingList pendingTxn) {
        //查询CustomerQualification数据是否存在
        CustomerQualification qualification = checkQualification(pendingTxn.getPendingNum());
        if(qualification == null){
            return new BaseResult(BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getCode(),BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getDesc());
        }

        //将CustomerQualification的APPROVED栏位标记为 Y,代表审批通过,同时将PendingNumber设置为null
        if(qualificationMapper.updateApprove(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        //将Pending表中的status修改为APP,代表审批通过
        if(pendingListService.updatePendingTxn(PendingList.makeApprove(pendingTxn)) < 0){
            return new BaseResult(BaseStatus.PENDING__DATA_EXCEPTION.getCode(),BaseStatus.PENDING__DATA_EXCEPTION.getDesc());
        }

        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.PENDING_APPROVE_SUCCESS.getDesc());
    }

    @Override
    @Transactional
    public BaseResult rejectDeletePending(PendingList pendingTxn) {
        //查询CustomerQualification数据是否存在
        CustomerQualification qualification = checkQualification(pendingTxn.getPendingNum());
        if(qualification == null){
            return new BaseResult(BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getCode(),BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getDesc());
        }

        //将审批数据的状态改为REJ.
        if(pendingListService.updatePendingTxn(PendingList.makeReject(pendingTxn)) <= 0){
            return new BaseResult(BaseStatus.PENDING__DATA_EXCEPTION.getCode(),BaseStatus.PENDING__DATA_EXCEPTION.getDesc());
        };

        //将CustomerQualification数据的PendingNumber设置为null
        if(qualificationMapper.updateReject(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.PENDING_REJECT_SUCCESS.getDesc());
    }

    @Override
    @Transactional
    public BaseResult approveDeletePending(PendingList pendingTxn) {
        //查询CustomerQualification数据是否存在
        CustomerQualification qualification = checkQualification(pendingTxn.getPendingNum());
        if(qualification == null){
            return new BaseResult(BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getCode(),BaseStatus.QUALIFICATION_DATA_NOT_EXIST.getDesc());
        }


        //將Pending记录状态修改为APP.
        if(pendingListService.updatePendingTxn(PendingList.makeApprove(pendingTxn)) <= 0){
            return new BaseResult(BaseStatus.PENDING__DATA_EXCEPTION.getCode(),BaseStatus.PENDING__DATA_EXCEPTION.getDesc());
        };

        //物理删除CustomerQualification数据
        if(qualificationMapper.physicsDeleteQualification(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.PENDING_APPROVE_SUCCESS.getDesc());
    }

    @Override
    @Transactional
    public BaseResult rejectModifyPending(PendingList pendingTxn) {
        //根据PendingNumber查询出CustomerQualification
        CustomerQualification  qualification = qualificationMapper.getQualificationByPendingNumber(pendingTxn.getPendingNum());

        //将审批数据的状态改为REJ.
        if(pendingListService.updatePendingTxn(PendingList.makeReject(pendingTxn)) <= 0){
            return new BaseResult(BaseStatus.PENDING__DATA_EXCEPTION.getCode(),BaseStatus.PENDING__DATA_EXCEPTION.getDesc());
        };

        //将CustomerQualification的PendingNumber设置为null
        if(qualificationMapper.updateReject(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        //将临时表中的数据进行物理删除
        if(qualificationMapper.physicsDeleteTemporaryQualification(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.PENDING_REJECT_SUCCESS.getDesc());
    }

    @Override
    @Transactional
    public BaseResult approveModifyPending(PendingList pendingTxn) {
        //根据PendingNumber查询出CustomerQualification
        CustomerQualification  qualificationOld = qualificationMapper.getQualificationByPendingNumber(pendingTxn.getPendingNum());

        //根据PendingNumber查询出CustomerNew
        CustomerQualification qualificationNew = qualificationMapper.getTemporaryQualification(pendingTxn.getPendingNum());

        //将PendingTxn状态改为APP.
        if(pendingListService.updatePendingTxn(PendingList.makeApprove(pendingTxn)) <= 0){
            return new BaseResult(BaseStatus.PENDING__DATA_EXCEPTION.getCode(),BaseStatus.PENDING__DATA_EXCEPTION.getDesc());
        };

        //修改qualificationOld的数据
        qualificationOld.setProfessionalInvestor(qualificationNew.getProfessionalInvestor());
        qualificationOld.setExpirationDate(qualificationNew.getExpirationDate());
        qualificationOld.setAllowedOption(qualificationNew.getAllowedOption());
        qualificationOld.setAllowedBookRate(qualificationNew.getAllowedBookRate());
        qualificationOld.setCreditRating(qualificationNew.getCreditRating());
        qualificationOld.setLoanCeiling(qualificationNew.getLoanCeiling());
        qualificationOld.setPrimeRate(qualificationNew.getPrimeRate());
        qualificationOld.setAssetLevel(qualificationNew.getAssetLevel());

        if(qualificationMapper.updateSourceQualification(qualificationOld) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        };

        //将临时表中的数据进行物理删除
        if(qualificationMapper.physicsDeleteTemporaryQualification(pendingTxn.getPendingNum()) <= 0){
            return new BaseResult(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.PENDING_APPROVE_SUCCESS.getDesc());
    }

    public CustomerQualification getCustomerQualificationByCusNo(Integer customerNo) {
        return qualificationMapper.getQualificationByCusNo(customerNo);
    }


    public Integer generateQualificationBatch(List<CustomerQualification> qualifications) {
        return qualificationMapper.insertQualification(qualifications);
    }

    private CustomerQualification checkQualification(Integer pendingNum) {
        return  qualificationMapper.getQualificationByPendingNumber(pendingNum);
    }

    public Integer updatePendingNumber(CustomerQualification qualification) {
        return qualificationMapper.updatePending(qualification);
    }

    public Integer addTemporaryData(CustomerQualification qualificationNew) {
        return qualificationMapper.addTemporaryQualification(qualificationNew);
    }

    public Boolean downloadPdf(List<CustomerQualification> qualificationList,String userName) {
        Boolean flag = true;

        String fileName = "客户资质信息.pdf";
        String path = "D:\\";
        // 定义全局的字体静态变量
        Font titlefont;
        Font headfont;
        Font keyfont = null;
        Font textfont = null;
        Font content = null;
        Font space1 = null;
        // 最大宽度
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 15, Font.NORMAL);
            content = new Font(bfChinese, 10, Font.NORMAL);
            space1 = new Font(bfChinese, 20, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //创建字体
            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            //使用字体并给出颜色
            font = new Font(bf,20,Font.BOLD, BaseColor.BLACK);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Document document = new Document(new RectangleReadOnly(842F, 595F));
        //设置页边距  60:左边距，60：右边距，72：上边距，72：下边距
        document.setMargins(60, 60, 72, 72);

        try {
            //给出输出路径
            PdfWriter.getInstance(document, new FileOutputStream(path+fileName));
            //打开生成的pdf文件
            document.open();
            //设置内容
            Paragraph paragraph = new Paragraph("客户资质信息", font);
            paragraph.setAlignment(1);
            //引用字体
            document.add(paragraph);

            // 设置表格的列宽和列数
            float[] widths = {25f,25f,25f,25f,25f,25f,25f,25f};
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(20f);
            // 设置表格宽度为100%
            table.setWidthPercentage(100.0F);
            table.setHeaderRows(1);
            table.getDefaultCell().setHorizontalAlignment(1);
            PdfPCell cell = null;

            cell = new PdfPCell(new Paragraph("资质到期日",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(20);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("客户号",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("客户名",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("专业投资机构",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("期权交易",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("预定汇率交易",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("征信等级",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("资产等级",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            for (CustomerQualification qualification :qualificationList){
                PdfPCell cell1 = new PdfPCell(new Paragraph(String.valueOf(qualification.getExpirationDate()), content));
                PdfPCell cell2 = new PdfPCell(new Paragraph(String.valueOf(qualification.getCustomerNo()), content));
                PdfPCell cell3 = new PdfPCell(new Paragraph(qualification.getCustomerName(), content));
                PdfPCell cell4 = new PdfPCell(new Paragraph(qualification.getProfessionalInvestor(), content));
                PdfPCell cell5 = new PdfPCell(new Paragraph(qualification.getAllowedOption(), content));
                PdfPCell cell6 = new PdfPCell(new Paragraph(qualification.getAllowedBookRate(), content));
                PdfPCell cell7 = new PdfPCell(new Paragraph(qualification.getCreditRating(), content));
                PdfPCell cell8= new PdfPCell(new Paragraph(qualification.getAssetLevel(), content));

                //单元格对齐方式
                cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell1.setFixedHeight(20);
                //单元格垂直对齐方式
                cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

                cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);

                cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);

                cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);

                table.addCell(cell1);
                table.addCell(cell2);
                table.addCell(cell3);
                table.addCell(cell4);
                table.addCell(cell5);
                table.addCell(cell6);
                table.addCell(cell7);
                table.addCell(cell8);
            }

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("导出人: " + userName,content));

            // 获取当前系统时间
            LocalDateTime now = LocalDateTime.now();

            // 使用DateTimeFormatter将LocalDateTime转换为String
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedString = now.format(formatter);
            //日期
            Paragraph paragraph8 = new Paragraph("导出日期: " + formattedString,content);
            //向右
            paragraph8.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph8);

            document.add(table);
            //关闭文档
            document.close();

        }catch (Exception e){
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


}
